package com.example.demo.config.login;

/**
 * fileName:CustomSessionManager
 * description: 自定义会话管理器
 * author: LJV
 * createTime:2022/4/14 14:24
 * version:1.0.0
 */

import com.example.demo.constant.RedisConstant;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.web.servlet.ShiroHttpServletRequest;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
import org.apache.shiro.web.util.WebUtils;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.io.Serializable;

/**
 * 自定义的sessionManager
 */
public class CustomSessionManager extends DefaultWebSessionManager {

    /**
     * 头信息中具有sessionid
     *      请求头：Authorization： sessionid
     *
     * 指定sessionId的获取方式
     */
    @Override
    protected Serializable getSessionId(ServletRequest request, ServletResponse response) {

        HttpServletRequest httpServletRequest = WebUtils.toHttp(request);
        //获取请求头Authorization中的数据
        String id = httpServletRequest.getHeader("Authorization");
        if(StringUtils.isEmpty(id)) {
            //如果没有携带，生成新的sessionId
            // 获取sessionId，id可以自定义
            return super.getSessionId(request, response);
        }else{
            //返回sessionId；
            request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID_SOURCE, "header"); //sessionID存放位置
            request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID, id);  //sessionId的值
            request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID_IS_VALID, Boolean.TRUE);  //是否需要验证
            return id;
        }
    }
}

